<style lang="less">
    @import '../../../styles/common.less';
</style>
<template>
    <card>
        <p slot="title">
            <Icon type="ios-glasses-outline" />
            表单模拟记录
        </p>
        <Row >
            <Col span="3">
            <Select  v-model="query1.name" placeholder="请选择查询条件" clearable @on-change="handleQuery1">
                <i-option  v-for="element in queryElements" :value="element.name" :key="element.name+'-label'">{{element.label}}</i-option>
            </Select>
            </Col>
            <Col span="4">
                <Input v-model="query1.value" placeholder="请输入查询值" style="margin-left: 5px" v-if="queryInputShow1"/>
                <DatePicker v-model="query1.value"  placeholder="Select date" style="margin-left: 5px" v-if="queryDatePickperShow1" :type="queryDatePickperType1" :format="queryDatePickperFormat1"></DatePicker>
            </Col>
            <Col span="4">
            <Select  v-model="query2.name" placeholder="请选择查询条件" clearable style="margin-left: 10px" @on-change="handleQuery2">
                <i-option  v-for="element in queryElements" :value="element.name" :key="element.name+'-label'">{{element.label}}</i-option>
            </Select>
            </Col>
            <Col span="4">
                <Input v-model="query2.value" placeholder="请输入查询值" style="margin-left: 15px" v-if="queryInputShow2"/>
                <DatePicker v-model="query2.value"  placeholder="Select date" style="margin-left: 15px" v-if="queryDatePickperShow2" :type="queryDatePickperType2" :format="queryDatePickperFormat2"></DatePicker>
            </Col>
            <Col span="4">
                <Button @click="handleRead" style="margin-left: 20px" type="primary" icon="search">搜索</Button>
            </Col>
        </Row>
        <Row class="margin-top-10 searchable-table-con1">
            <div>
                <Table refs="formTemplate" border :columns="columns" :data="records"></Table>
            </div>
        </Row>
        <Row class="margin-top-10 searchable-table-con1">
            <Page :total="totalCount" :page-size="size" show-total @on-change="changePage"></Page>
        </Row>
    </card>
</template>
<script>
    import api  from '../../../libs/api';
    import {eventBus} from "../../../libs/eventBus"
    import area from './custom_form/config/area'
    import preview from "./preview.vue"
    import {Message} from 'iview';
    export default {
        name: 'formRecord',
        components: {
            preview
        },
        data() {
            return {
                records:[],  //表单列表
                totalCount:0,//表单列表总页数
                current: 1,//当前页
                size: 10,//页面大小
                totalPage: 0, //总条数
                formNameQuery:"",//表单名称
                formCreateUserQuery:"", //表单创建人
                columns: [],
                filterElement:["tinymce"],//富文本不显示
                formTemplateId:"",
                queryElements:[],//查询条件
                query1:{element:"",name:"",value:""}, //查询条件1
                query2:{element:"",name:"",value:""}, //查询条件2
                queryDatePickperShow1:false, //查询条件1日期组件是否显示
                queryInputShow1:true,//查询条件1默认显示为输入框查询条件
                queryDatePickperType1:"date", //查询条件1日期组件类型
                queryDatePickperFormat1:"yyyy年MM月dd日", //查询条件1日期组件格式
                queryDatePickperShow2:false, //查询条件1日期组件是否显示
                queryInputShow2:true,//查询条件1默认显示为输入框查询条件
                queryDatePickperType2:"date", //查询条件2日期组件类型
                queryDatePickperFormat2:"yyyy年MM月dd日", //查询条件2日期组件格式
                queryFilterElement:["input","datepicker"],  //可以当查询条件的组件
            }
        },
        methods:{
            //查询条件1选择事件
            handleQuery1(row){
                let self=this;
                if(self.query2.name==row){
                    Message.warning({content:"查询条件重复",duration:3});
                    setTimeout(function () {
                        self.query1.name="";
                    },1000);
                }else{
                    self.queryElements.forEach(function (element) {
                        if(element.name==row){
                            if(element.element=="datepicker"){
                                self.queryDatePickperShow1=true;
                                self.queryDatePickperType1= (element.additional=='yyyy年MM月dd日') ? 'date' : 'datetime';
                                self.queryDatePickperFormat1=element.additional;
                                self.queryInputShow1=false;
                            }else{
                                self.queryDatePickperShow1=false;
                                self.queryInputShow1=true;
                            }
                            self.query1.value="";
                        }
                    })
                }

            },
            //查询条件2选择事件
            handleQuery2(row){
                let self=this;
                if(self.query1.name==row){
                    Message.warning({content:"查询条件重复",duration:3});
                    setTimeout(function () {
                        self.query2.name="";
                    },1000);
                }else{
                    self.queryElements.forEach(function (element) {
                        if(element.name==row){
                            if(element.element=="datepicker"){
                                self.queryDatePickperShow2=true;
                                self.queryDatePickperType2=(element.additional=='yyyy年MM月dd日') ? 'date' : 'datetime';
                                self.queryDatePickperFormat2=element.additional;
                                self.queryInputShow2=false;
                            }else{
                                self.queryDatePickperShow2=false;
                                self.queryInputShow2=true;
                            }
                            self.query2.value="";
                        }
                    })
                }
            },

            //获取地址
            getAddressValue(address, area, code = 0, str = "") {
                // 最后一步
                if (code == address.length - 1 && code == 3) return str + address[code];
                for (let i in area) {
                    if (area[i].value == address[code]) {
                        str = str + this.getAddressValue(address, area[i].children, code + 1, area[i].label);
                        break;
                    }
                }
                return str;
            },
            //表单记录查询事件
            handleRead(warn,constant){
                let self=this;
                if(self.formTemplateId==""&&warn){
                    Message.warning({content:"请选择表单模板",duration:3});
                    return false;
                }
                if(constant&&constant.formTemplateId){
                    self.formTemplateId=constant.formTemplateId;
                }
                let data={};
                let query=[];
                typeof self.query1.name!="undefined"&&self.query1.name!=""&&query.push(self.query1);
                typeof self.query2.name!="undefined"&&self.query2.name!=""&&query.push(self.query2);
                if(query.length!=0){
                    query.forEach(function (item) {
                        self.queryElements.forEach(function(queryItem){
                            if(item.name==queryItem.name){
                                item.element=queryItem.element;
                                item.additional=queryItem.additional;
                            }
                        })
                    });
                    let formRecord={};
                    formRecord.formDataView=query;
                    formRecord.formTemplateId=self.formTemplateId;
                    data.formRecordQuery=formRecord;
                }
                data.current = self.current;
                data.size = self.size;
                self.$get(api.formTemplates.base+"/"+self.formTemplateId).then(resp=> {
                    if (200 == resp.code) {
                        let formTemplate = JSON.parse( resp.obj.formTemplate || '[]');
                        this.$get(api.formTemplates.record.base.replace("{templateId}",this.formTemplateId),data).then(response=>{
                            if(200==response.code){
                                self.handleDynamicTable(response.obj,formTemplate);
                                self.totalPage = self.util.calTotalPage(response.obj.total, self.size);
                                self.totalCount = response.obj.total;
                            }
                        });
                    }
                });
            },
            //翻页
            changePage(index){
                this.current = index;
                this.handleRead(true);
            },
            //删除表单记录
            handleDelete(formTemplateId,id){
                this.$delete(api.formTemplates.record.base.replace("{templateId}",formTemplateId)+"/"+id,{}).then(response=>{
                    if(200==response.code){
                        this.handleRead(true);
                    }
                })
            },
            //清空查询条件
            handleClearQuery(){
                this.queryElements=[];//查询条件
                this.query1={element:"",name:"",value:""}; //查询条件1
                this.query2={element:"",name:"",value:""};//查询条件2
            },
            //动态生成table
            handleDynamicTable(page,formTemplate){
                let self=this;
                self.columns=[];//清空表头
                self.records=[];//清空数据
                if(page.total>0){
                    //点击了不同模板
                    if(self.formTemplateId!=page.records[0].formTemplateId){
                        self.handleClearQuery();
                    }
                    //header
                    let one=[];
                    //模板发生变更加载不同模板的查询条件
                    self.queryElements=[];
                    if(formTemplate.length!=page.records[0].formDataView.length){
                        page.records[0].formDataView.forEach(function(view){
                            formTemplate.forEach(function(template){
                                if(view.name==template.obj.name){
                                    one.push(view);
                                    self.queryElements.push(view);
                                }
                            });
                        });
                    }else{
                        one=page.records[0].formDataView;
                        Object.assign(self.queryElements,one);
                    }

                    //过滤查询组件
                    self.queryElements=self.queryElements.filter(v=>{
                        return self.queryFilterElement.indexOf(v.element)>=0;
                    });
                    self.formTemplateId=page.records[0].formTemplateId; //表单模板Id
                    //添加主键隐藏列
                    self.columns.push({title:"ID",key:"id"});
                    //过滤组件元素
                    one=one.filter(v => {
                        return self.filterElement.indexOf(v.element)<0;
                    });
                    //上传附件
                    one.forEach(function(element){
                        if(element.element=="uploads"){
                            self.columns.push({title:element.label,key:element.name,render: (h, params) => {
                                let uploads=[];
                                for(let i in params.row[element.name]){
                                    uploads.push(h('a', {
                                        domProps:{
                                            href: api.baseURL + '/onlinePreview?url=' + encodeURIComponent(params.row[element.name][i].downloadUrl),
                                            target:"_blank"
                                        },
                                        on: {
                                            click: () => {

                                            }
                                        },
                                        style: {
                                            display:"block",
                                            marginBottom:"10px",
                                            width:"100%",
                                            whiteSpace:"nowrap",
                                            overflow:"hidden",
                                            textOverflow:"ellipsis"
                                        },
                                    },(typeof params.row[element.name][i].customFileName !="undefined"&&params.row[element.name][i].customFileName!=null)?params.row[element.name][i].customFileName:params.row[element.name][i].originalFileName));
                                }
                                return h('div',uploads);
                            }});
                        }else{
                            self.columns.push({title:element.label,key:element.name});
                        }
                    });
                    //添加操作列
                    self.columns.push({
                        title: '操作',
                        key: 'action',
                        width: 180,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.$get(api.formTemplates.base+"/"+self.formTemplateId).then(response=> {
                                                if (200 == response.code) {
                                                    this.$Modal.confirm({
                                                            width:700,
                                                            render: (h) => {
                                                                return h(preview,{
                                                                    // 组件 props
                                                                    props: {
                                                                        formTemplate: response.obj,
                                                                        mode:"formRecordView", //记录查看模式
                                                                        formTemplateId:self.formTemplateId, //模板Id
                                                                        formRecordId:params.row.id //数据ID
                                                                    }
                                                                })
                                                            }
                                                        },
                                                    );
                                                }
                                            })

                                        }
                                    }
                                }, '查看'),
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.$get(api.formTemplates.base+"/"+self.formTemplateId).then(response=> {
                                                if (200 == response.code) {
                                                    this.$Modal.confirm({
                                                            width:700,
                                                            loading:true,
                                                            render: (h) => {
                                                                return h(preview,{
                                                                    // 组件 props
                                                                    props: {
                                                                        formTemplate: response.obj,
                                                                        mode:"formRecordEdit", //记录查看模式
                                                                        formTemplateId:self.formTemplateId, //模板Id
                                                                        formRecordId:params.row.id //数据ID
                                                                    }
                                                                })
                                                            },
                                                            onOk: () => {
                                                                let modal = this;
                                                                modal.$data.buttonLoading = false;
                                                                eventBus.$emit('updateFormRecord',self.formTemplateId,params.row.id,modal);
                                                            },
                                                        },
                                                    );
                                                }
                                            })

                                        }
                                    }
                                }, '编辑'),
                                h('Poptip', {
                                    props: {
                                        confirm: true,
                                        title: '您确定要删除这条数据吗?',
                                        transfer: true
                                    },
                                    on: {
                                        'on-ok': () => {
                                            this.handleDelete(self.formTemplateId,params.row.id);
                                        }
                                    }
                                }, [
                                    h('Button', {
                                        style: {
                                            margin: '0 5px'
                                        },
                                        props: {
                                            type: 'error',
                                            size: 'small'
                                        }
                                    }, '删除')
                                ])
                            ]);
                        }
                    });
                    //data
                    for (let i in page.records) {
                        let formDataView=page.records[i].formDataView;  //每条数据
                        let record={};
                        //添加主键数据
                        record.id=page.records[i].id;
                        //数据行列转化
                        for(let j in formDataView){
                            for(let k in self.columns){
                                if(self.columns[k].key==formDataView[j].name&&self.filterElement.indexOf(formDataView[j].element)<0){
                                    if(formDataView[j].element=="address"){
                                        record[self.columns[k].key]=self.getAddressValue(formDataView[j].valueView.split(",",4),area);
                                    }else if(formDataView[j].element=="cascader"){
                                        record[self.columns[k].key]=formDataView[j].additional;
                                    }else{
                                        record[self.columns[k].key]=formDataView[j].valueView;
                                    }

                                }
                            }
                        }
                        self.records.push(record);
                    }
                }
                self.totalPage = self.util.calTotalPage(page.total, self.size);
                self.totalCount = page.total;
            }

        },
        mounted(){
            let self=this;
            eventBus.$on("dynamicTable",function(page,formTemplate){
                self.handleDynamicTable(page,formTemplate);
            });
            eventBus.$on("freshFormRecord",function (constant) {
                self.handleRead(false,constant);
            });
        }
    }
</script>